package org.budo.launcher.smart;

import java.io.File;
import java.util.logging.Level;

import org.budo.launcher.service.AbstractBudoLauncherService;
import org.smartboot.http.HttpBootstrap;
import org.smartboot.http.HttpRequest;
import org.smartboot.http.HttpResponse;
import org.smartboot.http.logging.RunLogger;
import org.smartboot.http.server.handle.HttpHandle;
import org.smartboot.servlet.ContainerRuntime;

/**
 * @author lmw
 */
public class BudoSmartLauncher extends AbstractBudoLauncherService {
    @Override
    public void run(String[] args) {
        long start = System.currentTimeMillis();

        String webapp = new File("src/main/webapp").getAbsolutePath();

        final ContainerRuntime containerRuntime = new ContainerRuntime();
        this.addRuntime(containerRuntime, new File(webapp));

        containerRuntime.start();
        final HttpBootstrap bootstrap = new HttpBootstrap();
        bootstrap.pipeline().next(new HttpHandle() {
            public void doHandle(HttpRequest request, HttpResponse response) {
                containerRuntime.doHandle(request, response);
            }
        });

        bootstrap.setBannerEnabled(false);
        bootstrap.setBufferPool(1024 * 1024 * 10, Runtime.getRuntime().availableProcessors(), 1024 * 4);
        bootstrap.setReadBufferSize(1024 * 4).setPort(8080).start();

        System.out.println("启动成功,耗时：" + (System.currentTimeMillis() - start) + "ms");

        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            @Override
            public void run() {
                containerRuntime.stop();
                bootstrap.shutdown();
            }
        }));
    }

    private void addRuntime(final ContainerRuntime containerRuntime, File path) {
        RunLogger.getLogger().log(Level.FINE, "start load: " + path.getAbsolutePath());

        try {
            containerRuntime.addRuntime(path.getAbsolutePath(), "/" + path.getName());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        RunLogger.getLogger().log(Level.FINE, "load servlet container: /" + path.getName() + " success!");
    }
}